import textwrap

from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, cmake_layout


class CompressorRecipe(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    # generators = "CMakeToolchain", "CMakeDeps"

    ## 如果需要自定义 CMakeToolchain, 则 self.generators 属性不能重复包含
    ## 在下面的 generate(self) 中 instantiated 一个
    generators = "CMakeDeps"

    def requirements(self):
        # self.requires("zlib/1.3.1")
        self.requires("spdlog/1.15.3")
        self.requires("fmt/11.2.0")

        # ==== 根据平台选择, 示例
        if False and self.settings.os == "Windows":
            self.requires("base64/0.4.0")

    def build_requirements(self):
        # 根据平台选择, 构建依赖的工具, 实例
        if False and self.settings.os != "Windows":
            self.tool_requires("cmake/3.27.9")

    def layout(self):
        cmake_layout(self)

    # ========================= 让自己的代码编译为 debug 版本
    # def configure(self):
    #   self.settings.build_type = "Debug"

    # =========================
    def generate(self):
        tc = CMakeToolchain(self)

        # 定义自定义的 vs_runtime block
        class CustomVSRuntime:
            # ========== 定义模板，直接设置 CMAKE_MSVC_RUNTIME_LIBRARY; 省流版
            # template = "set(CMAKE_MSVC_RUNTIME_LIBRARY {{ vs_runtimes }})"

            # ========== copy 修改自 原版
            template: str = textwrap.dedent("""\
                # Definition of VS runtime CMAKE_MSVC_RUNTIME_LIBRARY, from settings build_type,
                # compiler.runtime, compiler.runtime_type

                cmake_policy(GET CMP0091 POLICY_CMP0091)
                if(NOT "${POLICY_CMP0091}" STREQUAL NEW)
                    message(FATAL_ERROR "The CMake policy CMP0091 must be NEW, but is '${POLICY_CMP0091}'")
                endif()
                message(STATUS "Conan toolchain: Setting CMAKE_MSVC_RUNTIME_LIBRARY={{ vs_runtimes }}")
                set(CMAKE_MSVC_RUNTIME_LIBRARY "{{ vs_runtimes }}")
                """)

            def context(self):
                # 返回模板所需变量
                return {"vs_runtimes": "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL"}

        # 替换原有的 vs_runtime block
        tc.blocks["vs_runtime"] = CustomVSRuntime
        # tc.blocks["vs_runtime"].context
        tc.generate()
